<?php

namespace djepo\UserBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use djepo\UserBundle\Entity\UserCategory;
use djepo\UserBundle\Form\UserCategoryType;

use Symfony\Component\HttpFoundation\Response;

/**
 * UserCategory controller.
 *
 * @Route("/api/usercategory")
 */
class UserCategoryRestController extends Controller
{
    /**
     * Lists all UserCategory entities.
     *
     * @Route("/", name="usercategory")
     * @Method("POST")
     * @Template()
     */
    public function indexAction()
    {
        $jsonData = $this->get('request')->query->get('json');
        $userId = $this->get('request')->query->get('user');

        $serializer = $this->get('serializer');
        $categoryCollection = $serializer->deserialize($jsonData, 'ArrayCollection<djepo\UserBundle\Entity\Category>', 'json');
        
        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('djepoUserBundle:FosUser')->find($userId);

        $qb = $em->createQueryBuilder();
        $qb->select('u');
        $qb->from('djepoUserBundle:UserCategory','u');
        $qb->where('u.user = :user');
        $qb->setParameter('user',$user);
        $entities = $qb->getQuery()->getResult();
        foreach ($entities as $entity) {
            $em->remove($entity);
        }
        $em->flush();

        for ($i=0; $i < count($categoryCollection); $i++) { 
            $usercat = new UserCategory();
            $usercat->setUser($user);
            $category = $em->getRepository('djepoUserBundle:Category')->find($categoryCollection[$i]->getId());
            $usercat->setCategory($category);
            $em->persist($usercat);
            $em->flush();
        }

        return new Response("OK");
    }

}
